package com.huibeili.web.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huibeili.common.utils.DateUtils;
import com.huibeili.common.utils.WechatAppletDataUtils;
import com.huibeili.common.utils.WechatParam;
import com.huibeili.common.utils.bean.WechatSetting;
import com.huibeili.goods.domain.PmsGoods;
import com.huibeili.goods.service.IPmsGoodsService;
import com.huibeili.goods.service.IPmsTypeService;
import com.huibeili.marketing.service.GroupMarketingShowService;
import com.huibeili.marketing.service.PreSaleShowService;
import com.huibeili.marketing.service.TryMarketingShowService;
import com.huibeili.marketing.service.TrySkuApplyService;
import com.huibeili.order.service.IOrderApiService;
import com.huibeili.setting.bean.WechatPaySet;
import com.huibeili.setting.service.ILsPaySettingService;
import com.huibeili.sms.domain.*;
import com.huibeili.sms.service.*;
import com.huibeili.system.service.ISysNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author huibeili
 */
@Slf4j
@Component("ryTask")
public class RyTask {
    /**
     * 试用申请接口实现类
     */
    @Autowired
    private TrySkuApplyService trySkuApplyService;
    /**
     * 注入订单服务接口
     */
    @Autowired
    private IOrderApiService IOrderApiService;
    /**
     * 注入拼团活动服务接口
     */
    @Autowired
    private GroupMarketingShowService groupMarketingShowService;
    /**
     * 注入试用活动服务接口
     */
    @Autowired
    private TryMarketingShowService tryMarketingShowService;
    /**
     * 注入预售活动服务接口
     */
    @Autowired
    private PreSaleShowService preSaleShowService;
    @Resource
    private ISmsHomeNewProductService homeNewProductService;
    @Resource
    private ISmsHomeRecommendProductService homeRecommendProductService;
    @Resource
    private ISmsHomeBrandService homeBrandService;
    @Resource
    private ISmsHomeRecommendSubjectService homeRecommendSubjectService;
    @Resource
    private ISmsHomeAdvertiseService homeAdvertiseService;
    @Resource
    private ISysNoticeService sysNoticeService;
    @Resource
    private IPmsTypeService typeService;
    @Autowired
    private IPmsGoodsService pmsGoodsService;
    @Autowired
    private ITAppletVisitService appletVisitService;
    @Autowired
    private ITAppletPageVisitService appletPageVisitService;
    @Autowired
    private ITAppletVisitStaticService appletVisitStaticService;
    @Autowired
    private ILsPaySettingService paySettingService;



    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        //    System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params) {
        //      System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() {
        log.debug("getVisitPage......start");
        WechatPaySet wechatAppletPaySet = paySettingService.queryPaySet(0).getWechatAppletPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        WechatParam param = new WechatParam();
        String yesterday = DateUtils.parseDateToStr("yyyyMMdd", DateUtils.addDays(new Date(), -1));
        param.setBegin_date(yesterday);
        param.setEnd_date(yesterday);
        String json = WechatAppletDataUtils.getVisitPage(wechatSetting, param);
        JSONObject object = JSONObject.parseObject(json);
        JSONArray array = JSONArray.parseArray(object.get("list").toString());
        for (int i = 0; i < array.size(); i++) {
            TAppletPageVisit pageVisit = new TAppletPageVisit();
            pageVisit.setPagePath(array.getJSONObject(i).get("page_path").toString());
            pageVisit.setPageVisitUv((Integer) array.getJSONObject(i).get("page_visit_uv"));
            pageVisit.setPageVisitPv((Integer) array.getJSONObject(i).get("page_visit_pv"));
            pageVisit.setPageStaytimePv((BigDecimal) array.getJSONObject(i).get("page_staytime_pv"));
            pageVisit.setEntrypagePv((Integer) array.getJSONObject(i).get("entrypage_pv"));
            pageVisit.setExitpagePv((Integer) array.getJSONObject(i).get("exitpage_pv"));
            pageVisit.setPageSharePv((Integer) array.getJSONObject(i).get("page_share_pv"));
            pageVisit.setPageShareUv((Integer) array.getJSONObject(i).get("page_share_uv"));
            pageVisit.setCreateTime(new Date());
            pageVisit.setStoreId(0L);
            appletPageVisitService.insertTAppletPageVisit(pageVisit);

        }

        log.debug("getVisitPage......end");
    }

    /**
     * 清理 因为商品被删除 导致的数据关联问题 半小时一次
     */
   // @Scheduled(cron = "0 0/30 * ? * ?")
    private void clearGoodsRelate() {
        log.info("清理 因为商品被删除 导致的数据关联问题start = {}", new Date());
        List<SmsHomeRecommendProduct> homeRecommendProductList = homeRecommendProductService.selectSmsHomeRecommendProductList(new SmsHomeRecommendProduct());
        List<SmsHomeNewProduct> homeNewProducts = homeNewProductService.selectSmsHomeNewProductList(new SmsHomeNewProduct());
        List<PmsGoods> productList = pmsGoodsService.selectPmsGoodsList(new PmsGoods());
        List<Long> ids = productList.stream().map(PmsGoods::getId).collect(Collectors.toList());
        for (SmsHomeNewProduct product : homeNewProducts) {
            if (!ids.contains(product.getProductId())) {
                homeNewProductService.deleteSmsHomeNewProductById(product.getId());
            }
        }
        for (SmsHomeRecommendProduct product : homeRecommendProductList) {
            if (!ids.contains(product.getProductId())) {
                homeRecommendProductService.deleteSmsHomeRecommendProductById(product.getId());
            }
        }
        log.info("清理 因为商品被删除 导致的数据关联问题end = {}", new Date());
    }

    /**
     * 扫描已结束的试用促销，并随机抽取获得申请资格的人
     */
    //@Scheduled(cron = "0 0 2 * * ?")
    public void randomExtractApplyCustomer() {
        trySkuApplyService.randomExtractApplyCustomer();
    }

    /**
     * 确认收货
     */
   // @Scheduled(cron = "0 0 2 * * ?")
    public void autoConfirmReceipt() {
        IOrderApiService.autoConfirmReceipt();

    }

    /**
     * 取消订单
     */
   // @Scheduled(cron = "0 0 2 * * ?")
    public void autoCancelOrder() {
        IOrderApiService.autoCancelOrder();

    }

    /**
     * 处理超过24小时的拼团订单
     */
   // @Scheduled(cron = "0 0 0/2 * * ? ")
    public void autoCancelGroupOrder() {
        IOrderApiService.autoCancelGroupOrder();

    }

    /**
     * 自动取消定金预售订单
     */
   // @Scheduled(cron = "0 0 0 24 * ? ")
    public void autoCancelDepositPreSaleOrder() {
        IOrderApiService.autoCancelDepositPreSaleOrder();
    }

    /**
     * 处理已结束的众筹订单
     */
   // @Scheduled(cron = "0 0 2 * * ?")
    public void autoHandleCrowdFundingOrder() {
        IOrderApiService.autoHandleCrowdFundingOrder();
    }

    /**
     * 自动删除结束的拼团活动
     */
   // @Scheduled(cron = "0 0 0 * * ?")
    public void autoDeleteEndGroups() {
        groupMarketingShowService.autoDeleteEndGroups();
    }

    /**
     * 自动删除结束的试用活动
     */
   // @Scheduled(cron = "0 0 0 * * ?")
    public void autoDeleteEndTrys() {
        tryMarketingShowService.autoDeleteEndTrys();
    }

    /**
     * 自动删除结束的预售活动
     */
   // @Scheduled(cron = "0 0 0 * * ?")
    public void autoDeleteEndPreSales() {
        preSaleShowService.autoDeleteEndPreSales();
    }

    /**
     * 访问页面。目前只提供按 page_visit_pv 排序的 top200。
     */
   // @Scheduled(cron = "0 18 11 * * ? *")
    public void getVisitPage() {
        log.debug("getVisitPage......start");
        WechatPaySet wechatAppletPaySet = paySettingService.queryPaySet(0).getWechatAppletPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        WechatParam param = new WechatParam();
        String yesterday = DateUtils.parseDateToStr("yyyyMMdd", DateUtils.addDays(new Date(), -1));
        param.setBegin_date(yesterday);
        param.setEnd_date(yesterday);
        String json = WechatAppletDataUtils.getVisitPage(wechatSetting, param);
        JSONObject object = JSONObject.parseObject(json);
        JSONArray array = JSONArray.parseArray(object.get("list").toString());
        for (int i = 0; i < array.size(); i++) {
            TAppletPageVisit pageVisit = new TAppletPageVisit();
            pageVisit.setPagePath(array.getJSONObject(i).get("page_path").toString());
            pageVisit.setPageVisitUv((Integer) array.getJSONObject(i).get("page_visit_uv"));
            pageVisit.setPageVisitPv((Integer) array.getJSONObject(i).get("page_visit_pv"));
            pageVisit.setPageStaytimePv((BigDecimal) array.getJSONObject(i).get("page_staytime_pv"));
            pageVisit.setEntrypagePv((Integer) array.getJSONObject(i).get("entrypage_pv"));
            pageVisit.setExitpagePv((Integer) array.getJSONObject(i).get("exitpage_pv"));
            pageVisit.setPageSharePv((Integer) array.getJSONObject(i).get("page_share_pv"));
            pageVisit.setPageShareUv((Integer) array.getJSONObject(i).get("page_share_uv"));
            pageVisit.setCreateTime(new Date());
            pageVisit.setStoreId(0L);
            appletPageVisitService.insertTAppletPageVisit(pageVisit);

        }

        log.debug("getVisitPage......end");
    }

    /**
     * 获取小程序新增或活跃用户的画像分布数据。时间范围支持昨天、最近7天、最近30天。其中，新增用户数为时间范围内首次访问小程序的去重用户数，活跃用户数为时间范围内访问过小程序的去重用户数
     */
   // @Scheduled(cron = "0 18 11 * * ? *")
    public void getUserPortrait1() {
        log.debug("getUserPortrait......start");
        WechatPaySet wechatAppletPaySet = paySettingService.queryPaySet(0).getWechatAppletPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        WechatParam param = new WechatParam();
        String yesterday = DateUtils.parseDateToStr("yyyyMMdd", DateUtils.addDays(new Date(), -1));
        param.setBegin_date(yesterday);
        param.setEnd_date(yesterday);
        String json = WechatAppletDataUtils.getUserPortrait(wechatSetting, param);
        JSONObject object = JSONObject.parseObject(json);
        JSONObject visit_uv_new = JSONObject.parseObject(object.get("visit_uv_new").toString());
        JSONArray platforms = JSONArray.parseArray(visit_uv_new.get("platforms").toString());
        for (int i = 0; i < platforms.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(platforms.getJSONObject(i).getLong("id"));
            pageVisit.setName(platforms.getJSONObject(i).get("name").toString());
            pageVisit.setValue(platforms.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("4");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray devices = JSONArray.parseArray(visit_uv_new.get("devices").toString());
        for (int i = 0; i < devices.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(devices.getJSONObject(i).getLong("value"));
            pageVisit.setName(devices.getJSONObject(i).get("name").toString());
            pageVisit.setValue(devices.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("5");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray ages = JSONArray.parseArray(visit_uv_new.get("ages").toString());
        for (int i = 0; i < ages.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(ages.getJSONObject(i).getLong("id"));
            pageVisit.setName(ages.getJSONObject(i).get("name").toString());
            pageVisit.setValue(ages.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("6");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray genders = JSONArray.parseArray(visit_uv_new.get("genders").toString());
        for (int i = 0; i < genders.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(genders.getJSONObject(i).getLong("id"));
            pageVisit.setName(genders.getJSONObject(i).get("name").toString());
            pageVisit.setValue(genders.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("3");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }

        JSONArray province = JSONArray.parseArray(visit_uv_new.get("province").toString());
        for (int i = 0; i < province.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(province.getJSONObject(i).getLong("id"));
            pageVisit.setName(province.getJSONObject(i).get("name").toString());
            pageVisit.setValue(province.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("1");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray city = JSONArray.parseArray(visit_uv_new.get("city").toString());
        for (int i = 0; i < city.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(city.getJSONObject(i).getLong("id"));
            pageVisit.setName(city.getJSONObject(i).get("name").toString());
            pageVisit.setValue(city.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("2");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        /** 新增（1省，2市，3性别，4平台 5设备 6 年龄）
         留存（11省，12市，13性别，14平台 15设备 16 年龄） */

        log.debug("getUserPortrait......end");
    }

    /**
     * 获取小程序新增或活跃用户的画像分布数据。时间范围支持昨天、最近7天、最近30天。其中，新增用户数为时间范围内首次访问小程序的去重用户数，活跃用户数为时间范围内访问过小程序的去重用户数
     */
   // @Scheduled(cron = "0 18 11 * * ? *")
    public void getUserPortrait2() {
        log.debug("getUserPortrait2......start");
        WechatPaySet wechatAppletPaySet = paySettingService.queryPaySet(0).getWechatAppletPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        WechatParam param = new WechatParam();
        String yesterday = DateUtils.parseDateToStr("yyyyMMdd", DateUtils.addDays(new Date(), -1));
        param.setBegin_date(yesterday);
        param.setEnd_date(yesterday);
        String json = WechatAppletDataUtils.getUserPortrait(wechatSetting, param);
        JSONObject object = JSONObject.parseObject(json);
        JSONObject visit_uv_new = JSONObject.parseObject(object.get("visit_uv").toString());
        JSONArray platforms = JSONArray.parseArray(visit_uv_new.get("platforms").toString());
        for (int i = 0; i < platforms.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(platforms.getJSONObject(i).getLong("id"));
            pageVisit.setName(platforms.getJSONObject(i).get("name").toString());
            pageVisit.setValue(platforms.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("14");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray devices = JSONArray.parseArray(visit_uv_new.get("devices").toString());
        for (int i = 0; i < devices.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(devices.getJSONObject(i).getLong("value"));
            pageVisit.setName(devices.getJSONObject(i).get("name").toString());
            pageVisit.setValue(devices.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("15");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray ages = JSONArray.parseArray(visit_uv_new.get("ages").toString());
        for (int i = 0; i < ages.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(ages.getJSONObject(i).getLong("id"));
            pageVisit.setName(ages.getJSONObject(i).get("name").toString());
            pageVisit.setValue(ages.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("16");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray genders = JSONArray.parseArray(visit_uv_new.get("genders").toString());
        for (int i = 0; i < genders.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(genders.getJSONObject(i).getLong("id"));
            pageVisit.setName(genders.getJSONObject(i).get("name").toString());
            pageVisit.setValue(genders.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("13");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }

        JSONArray province = JSONArray.parseArray(visit_uv_new.get("province").toString());
        for (int i = 0; i < province.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(province.getJSONObject(i).getLong("id"));
            pageVisit.setName(province.getJSONObject(i).get("name").toString());
            pageVisit.setValue(province.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("11");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        JSONArray city = JSONArray.parseArray(visit_uv_new.get("city").toString());
        for (int i = 0; i < city.size(); i++) {
            TAppletVisitStatic pageVisit = new TAppletVisitStatic();
            pageVisit.setId(city.getJSONObject(i).getLong("id"));
            pageVisit.setName(city.getJSONObject(i).get("name").toString());
            pageVisit.setValue(city.getJSONObject(i).getLong("value"));
            pageVisit.setStoreId(0L);
            pageVisit.setType("12");
            pageVisit.setCreateTime(new Date());
            appletVisitStaticService.insertTAppletVisitStatic(pageVisit);
        }
        /** 新增（1省，2市，3性别，4平台 5设备 6 年龄）
         留存（11省，12市，13性别，14平台 15设备 16 年龄） */

        log.debug("getUserPortrait2......end");
    }

    /**
     * 获取用户访问小程序日留存
     */
    @Scheduled(cron = "0 18 11 * * ? *")
    public void getDailyRetain() {
        WechatPaySet wechatAppletPaySet = paySettingService.queryPaySet(0).getWechatAppletPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());

        WechatParam param = new WechatParam();

        String yesterday = DateUtils.parseDateToStr("yyyyMMdd", DateUtils.addDays(new Date(), -1));
        param.setBegin_date(yesterday);
        param.setEnd_date(yesterday);

        String json = WechatAppletDataUtils.getDailyRetain(wechatSetting, param);
        TAppletVisit visit = new TAppletVisit();
        visit.setStoreId(0L);
        visit.setCreateTime(new Date());
        JSONObject object = JSONObject.parseObject(json);
        JSONArray array = JSONArray.parseArray(object.get("visit_uv_new").toString());
        JSONObject visit_uv_new = JSONObject.parseObject(array.get(0).toString());
        visit.setDate(object.get("ref_date").toString());
        visit.setVisitUvNew(visit_uv_new.getInteger("value"));

        JSONArray array1 = JSONArray.parseArray(object.get("visit_uv").toString());
        JSONObject visit_uv = JSONObject.parseObject(array1.get(0).toString());
        visit.setVisitUv(visit_uv.getInteger("value"));

        String json1 = WechatAppletDataUtils.getDailyVisitTrend(wechatSetting, param);
        JSONObject object1 = JSONObject.parseObject(json1);
        JSONArray array11 = JSONArray.parseArray(object1.get("list").toString());

        visit.setSessionCnt(array11.getJSONObject(0).getInteger("session_cnt"));
        visit.setVisitPv(array11.getJSONObject(0).getInteger("visit_pv"));
        visit.setVisitUvAdd(array11.getJSONObject(0).getInteger("visit_uv"));
        visit.setVisitUvNewAdd(array11.getJSONObject(0).getInteger("visit_uv_new"));
        visit.setStayTimeUv(array11.getJSONObject(0).getBigDecimal("stay_time_uv"));
        visit.setStayTimeSession(array11.getJSONObject(0).getBigDecimal("stay_time_session"));
        visit.setVisitDepth(array11.getJSONObject(0).getBigDecimal("visit_depth"));

        String json2 = WechatAppletDataUtils.getDailySummary(wechatSetting, param);
        JSONObject object2 = JSONObject.parseObject(json2);
        JSONArray array22 = JSONArray.parseArray(object2.get("list").toString());

        visit.setVisitTotal(array22.getJSONObject(0).getInteger("visit_total"));
        visit.setSharePv(array22.getJSONObject(0).getInteger("share_pv"));
        visit.setShareUv(array22.getJSONObject(0).getInteger("share_uv"));

        appletVisitService.insertTAppletVisit(visit);


    }
}
